/*
	后台页面控制器
*/
'use strict';
var AV 			= require('leanengine');
let admin		= {};
/**
 * 后台登录页面
 * 2015.04.18  by 胡斌
 */
admin.loginPage = function(req,res) {
	var error=req.query.error;
	//console.log("loginPage:"+error);
	if(req.AV.user) return res.redirect('/admin/index');
  res.render('admin-login',{error:error});
}

/**
 * 后台索引页面
 * 2015.04.18  by 胡斌
 */
admin.indexPage = function(req, res) {
	//console.log("index");
	res.render('admin-index.html',{
		user:req.AV.user
	});
}

/**
 * 统计数据
 * 2016.05.05  by 胡斌
 */
admin.ajaxCount = function(req, res) {
	var date=moment().startOf('day').toISOString();
	AV.Promise.when(
	  AV.Query.doCloudQuery("select count(*) from Image where isSys=false and  createdAt > date('"+date+"')"),
	  AV.Query.doCloudQuery("select count(*) from Trip where createdAt > date('"+date+"')"),
	  AV.Query.doCloudQuery("select count(*) from _User where createdAt > date('"+date+"')"),
	  AV.Query.doCloudQuery("select count(*) from ReportLog where state=0")
	).then(function (r1, r2, r3, r4) {
	  res.json({image:r1.count,trip:r2.count,user:r3.count,report:r4.count});
	});
}

/**
 * 后台登录
 * 2015.04.18  by 胡斌
 */
admin.doLogin = function(req,res) {
	//console.log(req.body.email);
	var queryUser = new AV.Query(AV.User);
	queryUser.equalTo("email",req.body.email);
	queryUser.equalTo("emailVerified",true);
	queryUser.first().then(function(user){
		//console.log(user.get("roleName"));
		if(typeof(user)=="object"){
			return AV.User.logIn(user.get("username"),req.body.password);
		}else{
			return AV.Promise.error('用户不存在');//登录失败
		}
	}).then(function(user) {
			//console.log(user.get("username"));
			//跳转到profile页面。
			res.redirect('/admin/index');
	},function(error) {
		if(typeof(error)=="object"){error=error.message;}
		console.error(error);
		//登录失败，跳转到登录页面
		res.redirect('/admin-login?error='+error);
	});
}

/**
 * 后台登出
 * 2015.04.18  by 胡斌
 */
admin.doLogout = function(req,res) {
	AV.User.logOut();
	//console.log("doLogout");
  res.redirect('/admin-login');
}

/**
 * 后台登录页面
 * 2015.04.18  by 胡斌
 */
admin.doCkAuth = function(req,res,next) {
	//console.log(req.AV.user);
	if(!req.AV.user){// 判断用户是否已经登录
		res.redirect('/admin-login');
		return false;
	}else if(req.AV.user.get("adminRole")!="admin"){
		res.redirect('/admin-logout');
		return false;
	}
	next();
}

module.exports = admin;
